<?php

namespace app\common\model;

use app\common\model\WsarticleModel;
use app\common\model\WscateModel;
use app\common\model\WsmessageModel;
use think\Model;

class SiteColumnModel extends Model
{
    protected $pk = 'column_id'; //主键
    protected $autoWriteTimestamp = true; //自动时间
    // 定义时间戳字段名
    protected $createTime = 'column_create_time';
    protected $updateTime = 'column_update_time';

    // 模型事件
    protected static function init()
    {
        // 新增前
        self::beforeInsert(function ($value) {

            if ($value['column_icon'] == '') {
                $value['column_icon'] = 'icon-check-empty';
            }

            $value['column_title'] = $value['column_name'];

            // 栏目放在最后
            $value['column_sort'] = 1000000;

            return $value;
        });

        // 新增栏目后
        self::afterInsert(function ($value) {
            $siteid = $value['column_siteid'];

            // 更新排序
            $model = new SiteColumnModel;
            $model->update_sort($siteid);

            if (isset($siteid)) {
                // 删除缓存
                if (cache('?cache_columns_' . $siteid)) {
                    cache('cache_columns_' . $siteid, null);
                }
            }
        });

        // 更新栏目后
        self::afterUpdate(function ($value) {

            if (isset($value['column_siteid'])) {
                // 删除缓存
                if (cache('?cache_columns_' . $value['column_siteid'])) {
                    cache('cache_columns_' . $value['column_siteid'], null);
                }
            }

            if (cache('?cache_column_' . $value['column_id'])) {
                cache('cache_column_' . $value['column_id'], null);
            }

        });

        // 删除栏目前
        self::beforeDelete(function ($value) {
            // 判断是否有子栏目，存在子栏目不允许删除
            $id = $value['column_id'];
            $where = "column_path like '%," . $id . ",%' or column_path like '%," . $id . "'";
            $count = self::where($where)->count();
            if ($count > 0) {
                return false;
            }
        });

        // 删除栏目后
        self::afterDelete(function ($value) {
            // 删除文章
            WsarticleModel::where('wsarticle_columnid=' . $value['column_id'])->delete();

            // 删除分类
            WscateModel::where('wscate_columnid=' . $value['column_id'])->delete();

            // 删除留言
            WsmessageModel::where('wsmessage_columnid=' . $value['column_id'])->delete();

            if (isset($value['column_siteid'])) {
                // 删除缓存
                if (cache('?cache_columns_' . $value['column_siteid'])) {
                    cache('cache_columns_' . $value['column_siteid'], null);
                }
            }

            if (cache('?cache_column_' . $value['column_id'])) {
                cache('cache_column_' . $value['column_id'], null);
            }
        });
    }

    // 图片进行序列化
    public function setColumnImageAttr($value)
    {
        return serialize($value);
    }

    // 序列化
    public function getColumnImageAttr($value)
    {
        return unserialize($value);
    }

    // 获取器 column_cate_html 新添加字段
    public function getColumnCateHtmlAttr($value, $data)
    {
        $value = $data['column_cate'];
        $status = [
            0 => '&nbsp;',
            1 => '<label class="label label-success">单选</label>',
            2 => '<label class="label label-info">多选</label>',
        ];
        return isset($status[$value]) ? $status[$value] : '';
    }

    // 获取器 column_field_html 新添加字段
    public function getColumnFieldHtmlAttr($value, $data)
    {
        $value = $data['column_field'];
        $status = [
            0 => '&nbsp;',
            1 => '<label class="label label-success">启用</label>',
        ];
        return isset($status[$value]) ? $status[$value] : '';
    }

    // 模型关联
    public function module()
    {
        $field = 'module_id,module_name,module_path';
        return $this->hasOne('ModuleModel', 'module_id', 'column_moduleid')->bind($field);
    }

    /**
     * [tree_to_data 对 树型tree 数据 进行调整]
     * @param  [type]  $tree  [description]
     * @param  integer $pid   [description]
     * @param  string  $path  [description]
     * @param  array   &$list [description]
     * @return [type]         [description]
     */
    public function tree_to_data($tree, $pid = 0, $path = '0', &$list = array())
    {
        static $sort = 0;
        //dump($tree);
        if (is_array($tree)) {
            foreach ($tree as $key => $item) {
                $sort++;
                $reffer = $item;
                unset($reffer['children']);
                $reffer['column_sort'] = $sort;
                $reffer['column_pid'] = $pid;
                $reffer['column_path'] = $path;
                $reffer['column_child'] = 0;
                if (isset($item['children']) and count($item['children']) > 0) {
                    $reffer['column_child'] = 1;
                    $reffer['column_moduleid'] = 0;
                }
                $list[] = $reffer;

                if (isset($item['children'])) {
                    $mypath = $reffer['column_path'] . ',' . $reffer['column_id'];
                    self::tree_to_data($item['children'], $item['column_id'], $mypath, $list);
                }
            }
        }
        return $list;
    }

    /**
     * [tree_to_html 生成html页面]
     * @param  [type]  $tree [description]
     * @param  integer $num  [description]
     * @return [type]        [description]
     */
    public function tree_to_html($tree, $num = 0)
    {
        $html = '';
        $num++;
        foreach ($tree as $item) {
            $html .= '<li class="dd-item" data-column_id="' . $item['column_id'] . '">';
            $html .= '  <div class="dd-handle">' . $item['column_name'] . '</div>';
            if (isset($item['children']) and count($item['children']) > 0) {
                if ($num < 3) {
                    $html .= '<ol class="dd-list">';
                    $html .= self::tree_to_html($item['children'], $num);
                    $html .= '</ol>';
                }
            }
            $html .= '</li>';
        }
        return $html;
    }

    /**
     * [update_sort 更新栏目排序]
     * @param  [type] $siteid [description]
     * @return [type]         [description]
     */
    public function update_sort($siteid = 0)
    {
        if ($siteid <= 0) {
            return false;
        }

        // 栏目自动排序
        $where = 'column_siteid = ' . $siteid;
        $field = 'column_id, column_pid, column_path';
        $order = 'column_sort asc, column_id asc';
        $list = self::where($where)->field($field)->order($order)->select()->toArray();

        // 生成树
        $tree = list_to_tree($list, 'column_id', 'column_pid');

        // 保存
        $data = self::tree_to_data($tree);
        self::saveAll($data);

        unset($list, $tree, $data);
    }
}
